import web
f=open("stocks")
lines=f.readlines()
stocks=list()
pinyinDict=dict()
codeDict=dict()
sortedPinyin=list()
sortedCode=list();
for i in lines:
  seq = i.strip().split()
  stocks.append(seq);
  pinyinDict[seq[1]]=seq;  
  codeDict[seq[0]]=seq;

sortedPinyin=pinyinDict.keys()
sortedPinyin.sort()
sortedCode=codeDict.keys()     
sortedCode.sort()

#for i in sortedPinyin:
#  print i; 
def getFromCode(src):
  begin=0
  end=0
  pos=0
  for c in src:
    i=begin
    flag=False
    while i<len(sortedCode):
      if len(sortedCode[i])>pos and c==sortedCode[i][pos] and not flag:
        begin=i
        flag=True;
      if flag and c!=sortedCode[i][pos]:
        end=i
        break
      #if flag:
      #  print pos,i,sortedCode[i]
      i=i+1
    pos=pos+1
  res = list()
  i=begin
  while i<end:
    res.append(codeDict[sortedCode[i]])
    i=i+1
    if len(res)>=10:
      break
  return res


def getFromPinyin(src):
  begin=0
  end=0
  pos=0
  for c in src:
    i=begin
    flag=False
    while i<len(sortedPinyin):
      if len(sortedPinyin[i])>pos and c==sortedPinyin[i][pos] and not flag:
        begin=i
        flag=True;
      if flag and c!=sortedPinyin[i][pos]:
        end=i
        break
      #if flag:
      #  print pos,i,sortedPinyin[i]
      i=i+1
    pos=pos+1
  res = list()
  i=begin
  while i<end:
    res.append(pinyinDict[sortedPinyin[i]])
    if len(res)>=10:
      break
    i=i+1
  return res
#res=getFromPinyin("qc")
#for i in res:
#  print i
#res = getFromCode("60021")
#for i in res:
#  print i
urls=(
      '/(.*)','index'
)
app=web.application(urls,globals())
class index:
  def GET(self, name):
    i=web.input()
    print i
    #if not i.has("src"):
    #  return ""
    if len(i.src)==0:
       return ""
    res=list()
    if i.src[0]>'0' and i.src[0]<'9':
      res = getFromCode(i.src)
    else:
      res = getFromPinyin(i.src)
    resstr=""
    for r in res:
      resstr = "%s['%s','%s']," % (resstr, r[0], r[2])
    resstr = "[" + resstr[:-1] + "]"
    return resstr
if __name__=='__main__':
  app.run()

